<script lang="ts" setup>
import type { HandCardTypeApi } from '#/api/spa/handcard/type';

import { computed, ref } from 'vue';
import { message } from 'ant-design-vue';
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { $t } from '#/locales';
import { createHandCardType, getHandCardType, updateHandCardType } from '#/api/spa/handcard/type';

import { useFormSchema } from '../data';
import GoodsBinder from './goods-binder.vue';

const emit = defineEmits(['success']);
const formData = ref<HandCardTypeApi.HandCardType>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['手牌类型'])
    : $t('ui.actionTitle.create', ['手牌类型']);
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const values = (await formApi.getValues()) as any;
    const data = { ...values } as HandCardTypeApi.HandCardType;
    // 保证 goodsIdss/goodsInfo 为 JSON 数组（优先从表单字段读取，其次用本地 ref 兜底）
    const composite = values.goodsInfo;
    if (Array.isArray(composite)) {
      // 情况一：schema 直接绑定的是 info 对象数组
      (data as any).goodsInfo = composite;
      (data as any).goodsIdss = composite.map((it: any) => it?.goodsId).filter((v: any) => v !== undefined && v !== null);
    } else if (composite && (Array.isArray(composite.ids) || Array.isArray(composite.info))) {
      // 情况二：schema 绑定的是 { ids, info }
      (data as any).goodsIdss = Array.isArray(composite.ids) ? composite.ids : [];
      (data as any).goodsInfo = Array.isArray(composite.info) ? composite.info : [];
    } else {
      // 情况三：兜底使用子组件本地状态
      const submitIds = goodsIdssRef.value?.map((it: any) => (it && typeof it === 'object' ? it.value : it)) || [];
      const submitInfos = Array.isArray(goodsInfoRef.value) ? goodsInfoRef.value : [];
      (data as any).goodsIdss = submitIds;
      (data as any).goodsInfo = submitInfos;
    }

    try {
      await (formData.value?.id ? updateHandCardType(data) : createHandCardType(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      goodsIdssRef.value = [];
      goodsInfoRef.value = [];
      return;
    }
    // 加载数据
    let data = modalApi.getData<HandCardTypeApi.HandCardType>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await getHandCardType(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    // 设置到 values，并兼容字符串/JSON字符串/数组三种返回格式
    formData.value = data as any;
    const nextValues: any = { ...formData.value };
    const normalizeToArray = (val: any) => {
      if (Array.isArray(val)) return val;
      if (typeof val === 'string') {
        const t = val.trim();
        if (t.startsWith('[') && t.endsWith(']')) {
          try {
            const arr = JSON.parse(t);
            return Array.isArray(arr) ? arr : [];
          } catch {}
        }
        return t
          .split(',')
          .map((s: string) => (s || '').trim())
          .filter((s: string) => s !== '')
          .map((s: string) => {
            const n = Number(s);
            return Number.isNaN(n) ? s : n;
          });
      }
      return [];
    };
    const ids = normalizeToArray(nextValues.goodsIdss);
    // goodsInfo 可能是对象数组、JSON 字符串或名称数组
    let infos: any[] = [];
    if (Array.isArray(nextValues.goodsInfo)) {
      infos = nextValues.goodsInfo;
    } else if (
      typeof nextValues.goodsInfo === 'string' &&
      nextValues.goodsInfo.trim().startsWith('[')
    ) {
      try {
        const parsed = JSON.parse(nextValues.goodsInfo);
        if (Array.isArray(parsed)) infos = parsed;
      } catch {}
    } else {
      infos = normalizeToArray(nextValues.goodsInfo).map((name: any, i: number) => ({
        goodsId: ids[i],
        goodsName: name,
      }));
    }
    // 回显：同步到表单字段（schema 组件）与子组件本地状态
    goodsIdssRef.value = ids.map((id: any, idx: number) => ({
      label: infos[idx]?.goodsName ?? String(id),
      value: id,
    }));
    goodsInfoRef.value = infos;
    await formApi.setValues({
      ...nextValues,
      goodsInfo: { ids, info: infos },
    });
  },
});

// 本地状态：与子组件双向绑定
const goodsIdssRef = ref<any[]>([]);
const goodsInfoRef = ref<any[]>([]);
</script>

<template>
  <Modal :title="getTitle" class="w-3/4">
    <div class="mx-4">
      <Form class="w-full" />
    </div>
  </Modal>
</template>
